import 'package:flutter/material.dart';
import 'package:shop/cart.dart';
import 'package:shop/profile.dart';
import 'package:shop/product_detail.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class HomeApp extends StatefulWidget {
  @override
  State<HomeApp> createState() => _HomeAppState();
}

class _HomeAppState extends State<HomeApp> {
  // 当前选中的品牌，null 表示显示所有商品
  String? selectedBrand;

  // 商品信息数组
  final List<Map<String, dynamic>> products = [
    {
      'imageUrl':
          'https://img14.360buyimg.com/n7/jfs/t1/170405/38/52547/51897/672a0612F5f5a7189/c6d4d686cf782caa.jpg',
      'name': '小米 Redmi K70 Pro',
      'price': 3299,
      'description': '天玑9300-U 第二代超清光影像 1.5K高亮护眼屏'
    },
    {
      'imageUrl':
          'https://img12.360buyimg.com/n7/jfs/t1/249536/10/22883/42768/6729ea0fF904dc6e3/b828e354f735161c.jpg',
      'name': '华为 畅享70 Pro',
      'price': 1999,
      'description': '8GB+256GB 5G手机 全网通 曜金黑'
    },
    {
      'imageUrl':
          'https://img12.360buyimg.com/n7/jfs/t1/244865/29/21900/63301/67233836Ff385fd4d/fc4a474711a93783.jpg',
      'name': 'OPPO Reno11',
      'price': 2499,
      'description': '12GB+256GB 微醺 新品5G手机'
    },
    {
      'imageUrl':
          'https://img11.360buyimg.com/n7/jfs/t1/227698/26/28376/80505/67275955F5eee13cd/1c97fadb77401263.jpg',
      'name': 'vivo Y100t',
      'price': 1599,
      'description': '12GB+512GB 5G手机 极夜黑'
    },
    {
      'imageUrl':
          'https://img11.360buyimg.com/n7/jfs/t1/158968/35/50490/80923/6728af3aF1932588e/556ded468e6fb71e.jpg',
      'name': '小米14',
      'price': 3999,
      'description': '徕卡光学 骁龙8Gen3 超轻薄玻璃机身'
    },
    {
      'imageUrl':
          'https://img14.360buyimg.com/n7/jfs/t1/167998/26/50517/59548/67289bc6F01b1e97d/00577f15de4bdb2f.jpg',
      'name': 'iQOO Neo9 Pro',
      'price': 2799,
      'description': '12GB+256GB 赛道版 骁龙8+旗舰芯'
    },
    {
      'imageUrl':
          'https://img14.360buyimg.com/n7/jfs/t1/170405/38/52547/51897/672a0612F5f5a7189/c6d4d686cf782caa.jpg',
      'name': 'HONOR X50i+',
      'price': 1399,
      'description': '8GB+256GB 5G手机 极光蓝'
    },
    {
      'imageUrl':
          'https://img11.360buyimg.com/n1/s450x450_jfs/t1/262459/1/372/88040/676405afF8a5ad662/cdc3ae64c616943b.jpg.avif',
      'name': 'Redmi Note 13 Pro+',
      'price': 1899,
      'description': '天玑7200-Ultra 1.5K超清曲面屏'
    },
    {
      'imageUrl':
          'https://img14.360buyimg.com/n7/jfs/t1/188307/20/47818/72888/66f0b2a6F175a81c7/5b9ffcbdf2476654.jpg.avif',
      'name': 'OPPO Find N3',
      'price': 8999,
      'description': '16GB+512GB 折叠屏 微醺金'
    },
    {
      'imageUrl':
          'https://img12.360buyimg.com/n7/jfs/t1/249536/10/22883/42768/6729ea0fF904dc6e3/b828e354f735161c.jpg',
      'name': 'vivo X100 Pro',
      'price': 6999,
      'description': '16GB+512GB 5G手机 暮光森林'
    },
  ];

  // 获取所有品牌列表
  List<String> get brands {
    // 定义品牌映射规则
    final brandMap = {
      'Redmi': '小米', // Redmi 归属于小米
      'HONOR': 'HONOR', // 保持原品牌名
      'OPPO': 'OPPO',
      'vivo': 'vivo',
      'iQOO': 'vivo', // iQOO 归属于 vivo
      '华为': '华为',
      '小米': '小米',
    };

    final brandSet = products.map((p) {
      String productName = p['name'].toString();
      // 处理特殊情况：小米14 应该归类到小米品牌
      if (productName.startsWith('小米')) {
        return '小米';
      }
      String brandName = productName.split(' ')[0];
      return brandMap[brandName] ?? brandName;
    }).toSet();
    return brandSet.toList()..sort();
  }

  // 根据选中的品牌过滤商品
  List<Map<String, dynamic>> get filteredProducts {
    if (selectedBrand == null) return products;

    return products.where((p) {
      String productName = p['name'].toString();
      // 处理特殊情况：小米14 应该归类到小米品牌
      if (selectedBrand == '小米' && productName.startsWith('小米')) {
        return true;
      }
      String brandName = productName.split(' ')[0];

      // 处理特殊品牌归属关系
      if (selectedBrand == '小米' &&
          (brandName == 'Redmi' || brandName == '小米')) {
        return true;
      }
      if (selectedBrand == 'vivo' &&
          (brandName == 'iQOO' || brandName == 'vivo')) {
        return true;
      }

      return brandName == selectedBrand;
    }).toList();
  }

  // 添加购物车列表
  final List<Map<String, dynamic>> cartItems = [];
  int _currentIndex = 0;

  // 添加轮播图数据
  final List<String> carouselImages = [
    'assets/images/banner1.jpg',
    'assets/images/banner2.jpg',
    'assets/images/banner3.jpg',
    'assets/images/banner4.jpg',
  ];

  // 添加当前轮播图索引
  // int _currentCarouselIndex = 0;

  // 添加到购物车方法
  void addToCart(Map<String, dynamic> product) {
    setState(() {
      // 检查商品是否在购物车中
      final existingItem = cartItems.firstWhere(
        (item) => item['name'] == product['name'],
        orElse: () => Map<String, dynamic>.from({}),
      );

      if (existingItem.isEmpty) {
        // 如果商品不在购物车中，添加新商品
        cartItems.add({
          ...product,
          'quantity': 1,
        });
      } else {
        // 如果商品已在购物车中，增加数量
        existingItem['quantity'] = (existingItem['quantity'] as int) + 1;
      }
    });
  }

  // 从购物车移除商品
  void removeFromCart(Map<String, dynamic> item) {
    setState(() {
      cartItems.remove(item);
    });
  }

  // 添加品牌 Logo 映射
  final Map<String, String> brandLogos = {
    '小米':
        'https://cdn.cnbj1.fds.api.mi-img.com/mi.com-assets/shop/img/logo-mi2.png',
    'HONOR':
        'https://img2.baidu.com/it/u=4212747372,3384396776&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
    'OPPO':
        'https://img1.baidu.com/it/u=3334746430,239181568&fm=253&fmt=auto?w=600&h=424',
    'vivo':
        'https://img1.baidu.com/it/u=510887545,3842704366&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=487',
    '华为':
        'https://img0.baidu.com/it/u=2007219514,3684347995&fm=253&fmt=auto&app=138&f=JPEG?w=808&h=800',
  };

  @override
  Widget build(BuildContext context) {
    // 创建页面列表
    final pages = [
      // 主页内容
      ListView(
        children: [
          // 添加轮播图组件
          Container(
            height: 200,
            child: Swiper(
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  width: MediaQuery.of(context).size.width,
                  margin: const EdgeInsets.symmetric(horizontal: 0),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(carouselImages[index]),
                      fit: BoxFit.fill,
                    ),
                  ),
                );
              },
              itemCount: carouselImages.length,
              pagination: const SwiperPagination(
                alignment: Alignment.bottomCenter,
                builder: DotSwiperPaginationBuilder(
                  activeColor: Colors.blue,
                  color: Colors.white,
                ),
              ),
              autoplay: true,
              autoplayDelay: 3000,
            ),
          ),
          // 品牌分类网格
          GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 4,
            padding: const EdgeInsets.all(10),
            children: [
              // 添加"全部"选项
              Card(
                color: selectedBrand == null ? Colors.blue[100] : null,
                child: InkWell(
                  onTap: () {
                    setState(() {
                      selectedBrand = null;
                    });
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.all_inclusive, size: 30),
                      Text('\u5168\u90e8'), // "全部"
                    ],
                  ),
                ),
              ),
              // 品牌分类卡片
              ...brands.map((brand) => Card(
                    color: selectedBrand == brand ? Colors.blue[100] : null,
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          selectedBrand = brand;
                        });
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 30,
                            height: 30,
                            decoration: BoxDecoration(
                              image: DecorationImage(
                                image: NetworkImage(
                                  brandLogos[brand] ??
                                      'https://via.placeholder.com/30',
                                ),
                                fit: BoxFit.contain,
                              ),
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(brand),
                        ],
                      ),
                    ),
                  )),
            ],
          ),
          // 商品列表
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: filteredProducts.length,
            itemBuilder: (context, index) {
              final product = filteredProducts[index];
              return Card(
                margin: const EdgeInsets.all(8),
                child: ListTile(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ProductDetailPage(
                          product: product,
                          onAddToCart: addToCart,
                        ),
                      ),
                    );
                  },
                  leading: Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      image: DecorationImage(
                        image: NetworkImage(product['imageUrl']),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  title: Text(product['name']),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(product['description']),
                      Text(
                        '\u4ef7\u683c: \uffe5${product['price']}',
                        style: const TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  trailing: ElevatedButton(
                    onPressed: () {
                      addToCart(product);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: const Text(
                              '\u5df2\u6dfb\u52a0\u5230\u8d2d\u7269\u8f66'),
                          duration: const Duration(seconds: 1),
                        ),
                      );
                    },
                    child: const Text('\u52a0\u5165\u8d2d\u7269\u8f66'),
                  ),
                ),
              );
            },
          ),
        ],
      ),
      // 购物车页面
      CartPage(
        cartItems: cartItems,
        onRemoveItem: removeFromCart,
      ),
      // 个人中心页面
      const ProfilePage(),
    ];

    return Scaffold(
      appBar: AppBar(
        title: const Text('\u5546\u57ce\u4e3b\u9875'), // "商城主页"
        backgroundColor: Colors.white,
        actions: [
          // 只保留搜索按钮
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: CustomSearchDelegate(),
              );
            },
          ),
        ],
      ),
      // 使用抽屉菜单
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Text(
                '\u7528\u6237\u4e2d\u5fc3', // "用户中心"
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                ),
              ),
            ),
            ListTile(
              leading: const Icon(Icons.person),
              title: const Text('\u4e2a\u4eba\u4fe1\u606f'), // "个人信息"
              onTap: () {
                Navigator.pop(context);
                // 跳转到个人信息页面
              },
            ),
            ListTile(
              leading: const Icon(Icons.shopping_bag),
              title: const Text('\u6211\u7684\u8ba2\u5355'), // "我的订单"
              onTap: () {
                Navigator.pop(context);
                // 跳转到订单页面
              },
            ),
            ListTile(
              leading: const Icon(Icons.favorite),
              title: const Text('\u6211\u7684\u6536\u85cf'), // "我的收藏"
              onTap: () {
                Navigator.pop(context);
                // 跳转到收藏页面
              },
            ),
            ListTile(
              leading: const Icon(Icons.settings),
              title: const Text('\u8bbe\u7f6e'), // "设置"
              onTap: () {
                Navigator.pop(context);
                // 跳转到设置页面
              },
            ),
          ],
        ),
      ),
      // 修改底部导航栏
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '\u9996\u9875', // "首页"
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.shopping_cart),
            label: '\u8d2d\u7269\u8f66', // "购物车"
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '\u6211\u7684', // "我的"
          ),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
      body: pages[_currentIndex], // 根据当前索引显示对应页面
    );
  }
}

// 自定义搜索委托
class CustomSearchDelegate extends SearchDelegate {
  // 搜索历史记录
  final List<String> searchHistory = [
    '小米14',
    'OPPO Find N3',
    'vivo X100 Pro',
  ];

  // 热门搜索关键词
  final List<String> hotSearches = [
    '折叠屏',
    '5G手机',
    '骁龙8Gen3',
    '天玑9300',
  ];

  // 获取商品数据
  List<Map<String, dynamic>> get products => _HomeAppState().products;

  // 根据关键词搜索商品
  List<Map<String, dynamic>> searchProducts(String query) {
    return products.where((product) {
      final name = product['name'].toString().toLowerCase();
      final description = product['description'].toString().toLowerCase();
      final searchLower = query.toLowerCase();

      return name.contains(searchLower) || description.contains(searchLower);
    }).toList();
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () {
          if (query.isEmpty) {
            close(context, null);
          } else {
            query = '';
            showSuggestions(context);
          }
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    final searchResults = searchProducts(query);

    if (searchResults.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.search_off, size: 60, color: Colors.grey),
            SizedBox(height: 10),
            Text(
              '\u6ca1\u6709\u627e\u5230\u76f8\u5173\u5546\u54c1', // "没有找到相关商品"
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: searchResults.length,
      itemBuilder: (context, index) {
        final product = searchResults[index];
        return Card(
          margin: const EdgeInsets.all(8),
          child: ListTile(
            leading: Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: NetworkImage(product['imageUrl']),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            title: Text(product['name']),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(product['description']),
                Text(
                  '\u4ef7\u683c: \uffe5${product['price']}',
                  style: const TextStyle(
                    color: Colors.red,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            trailing: ElevatedButton(
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: const Text(
                        '\u5df2\u6dfb\u52a0\u5230\u8d2d\u7269\u8f66'),
                    duration: const Duration(seconds: 1),
                  ),
                );
              },
              child: const Text('\u52a0\u5165\u8d2d\u7269\u8f66'),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return ListView(
      children: [
        // 搜索历史
        if (query.isEmpty) ...[
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '\u5386\u53f2\u641c\u7d22', // "历史搜索"
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.delete_outline),
                  onPressed: () {
                    // 清空搜索历史
                  },
                ),
              ],
            ),
          ),
          Wrap(
            spacing: 8,
            children: searchHistory
                .map((term) => ActionChip(
                      label: Text(term),
                      onPressed: () {
                        query = term;
                        showResults(context);
                      },
                    ))
                .toList(),
          ),
          // 热门搜索
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              '\u70ed\u95e8\u641c\u7d22', // "热门搜索"
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Wrap(
            spacing: 8,
            children: hotSearches
                .map((term) => ActionChip(
                      label: Text(term),
                      onPressed: () {
                        query = term;
                        showResults(context);
                      },
                    ))
                .toList(),
          ),
        ],
        // 搜索建议
        if (query.isNotEmpty) ...[
          ...searchProducts(query).map((product) => ListTile(
                leading: Icon(Icons.search),
                title: Text(product['name']),
                onTap: () {
                  query = product['name'];
                  showResults(context);
                },
              )),
        ],
      ],
    );
  }
}
